{include file="$header" /}
<div class="mk-app-warp">
    <mk-table-header
        keyword-title="用户名、昵称、邮箱号、手机号关键词搜索"
        :add-url="addUrl"
        :del-url="delUrl"
        :rows="rows"
        @del="del()"
        @add="openDrawer()"
        @search="searchData($event)"
        date-title="注册时间：">
    </mk-table-header>
    <el-table
        :data="table"
        v-loading="loading"
        :default-sort="{prop: search.prop, order: search.order}"
        @sort-change="sortChange"
        @selection-change="checkSelected">
        <el-table-column type="expand">
            <template slot-scope="props">
                <el-form label-position="left"  label-width="130px">
                    <el-form-item label="当前积分：">
                        <span>{{props.row.now_integral}}</span>
                    </el-form-item>
                    <el-form-item label="历史积分：">
                        <span>{{props.row.history_integral}}</span>
                    </el-form-item>
                    <el-form-item label="余额：">
                        <span>{{props.row.balance}}</span>
                    </el-form-item>
                    <el-form-item label="签名：">
                        <span>{{props.row.describe}}</span>
                    </el-form-item>
                    <el-form-item label="生日：">
                        <span>{{props.row.birthday}}</span>
                    </el-form-item>
                    <el-form-item label="等级：">
                        <span>{{props.row.level}}</span>
                    </el-form-item>
                    <el-form-item label="登陆IP：">
                        <span>{{props.row.login_ip}}</span>
                    </el-form-item>
                    <el-form-item label="登陆次数：">
                        <span>{{props.row.login_count}}</span>
                    </el-form-item>
                    <el-form-item label="更新时间：">
                        <span>{{props.row.update_time}}</span>
                    </el-form-item>
                    <el-form-item label="注册时间：">
                        <span>{{props.row.create_time}}</span>
                    </el-form-item>
                </el-form>
            </template>
        </el-table-column>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="编号" sortable="custom"></el-table-column>
        <el-table-column prop="account" label="用户名" sortable="custom">
            <template slot-scope="scope">
                <el-image :src="domain + scope.row.cover" class="mk-table-cover">
                    <div slot="error" class="image-slot">
                        <img class="error-image" :src="static + '/images/error.png'"/>
                    </div>
                </el-image>
                {{scope.row.account}}
            </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" sortable="custom"></el-table-column>
        <el-table-column prop="group_title" label="所属组别" sortable="custom"></el-table-column>
        <el-table-column prop="email" label="邮箱号" sortable="custom"></el-table-column>
        <el-table-column prop="mobile" label="手机号" sortable="custom"></el-table-column>
        <el-table-column prop="status" label="状态" width="100px" sortable="custom">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="status(scope.row)"
                    :disabled="editAuthority === false">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in field" :label="item.label" :key="index">
            <template slot-scope="scope">
                <template v-for="(val, key) in scope.row.field" :key="index">
                    <component
                        v-if="val.field === item.field"
                        v-model="val.value"
                        :is="item.bind"
                        :key="item.name"
                        :type="item.type"
                        :format="item.format"
                        :value-format="item.valueFormat"
                        :options="region"
                        show-alpha>
                    </component>
                </template>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
                <mk-table-public
                    :edit-url="editUrl"
                    :del-url="delUrl"
                    @edit="openDrawer(scope.row)"
                    @del="del(scope.row)">
                </mk-table-public>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageChange"
        :current-page="search.page"
        :page-size="search.pageSize"
        :page-sizes="pageSizes"
        :total="pageTotal"
        layout="total, sizes, prev, pager, next, jumper"
        background
        hide-on-single-page>
    </el-pagination>
</div>
{include file="user/drawer" /}
{include file="$component" /}
<script>
    var group  = {:json_encode($group)};
    var config = {:json_encode($config)};
    var field  = {:json_encode($field)};
    new Vue({
        el: '#app',
        data() {
            var validateRepeatEmail = (rule, value, callback) => {
                if (typeof this.drawerData.id === 'undefined') {
                    let isExist = common.arrayIndex(this.table, value, 'email');
                    if(isExist !== -1) {
                        callback(new Error('邮箱号已存在！'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            }
            var validateRepeatMobile = (rule, value, callback) => {
                if (typeof this.drawerData.id === 'undefined') {
                    let isExist = common.arrayIndex(this.table, value, 'mobile');
                    if(isExist !== -1) {
                        callback(new Error('手机号已存在！'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            }
            var validateRepeatAccount = (rule, value, callback) => {
                if (typeof this.drawerData.id === 'undefined') {
                    let isExist = common.arrayIndex(this.table, value, 'account');
                    if(isExist !== -1) {
                        callback(new Error('账号已存在！'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            }
            return {
                rows: [],
                table: [],
                search:{
                    date: [],
                    keyword: "",
                    page: 1,
                    pageSize: 14,
                    prop: "id", 
                    order: "descending",
                },
                pageSizes: [14, 50, 100, 200, 500, 1000, 3000],
                pageTotal: 0,
                url: "user/index",
                addUrl: "user/save",
                delUrl: "user/delete",
                editUrl: "user/update",
                loading: false,
                group: tree.convertString(group), 
                drawer: false,
                drawerData: {},
                drawerForm: {
                    group_id: config.group_id,
                    nickname: "",
                    now_integral: 0,
                    history_integral: 0,
                    sex: 0,
                    email: "",
                    mobile: "",
                    account: "",
                    password: "",
                    cover: "",
                    describe: "",
                    birthday: "",
                    balance: 0.00,
                    level: 0,
                    status:1,
                    field: [],
                },
                drawerRules: {
                    group_id: [
                        { required: true, message: '请选择所属组别', trigger: 'blur' },
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'blur' },
                    ],
                    nickname: [
                        { required: true, message: '请输入用户昵称', trigger: 'blur' },
                        { min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入用户邮箱', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
                        { validator: validateRepeatEmail, trigger: 'blur' }
                    ],
                    account: [
                        { required: true, message: '请输入用户登录账号', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不能包含中文字符', trigger: 'blur' },
                        { min: 5, max: 40, message: '长度在 5 到 40 个字符', trigger: 'blur' },
                        { validator: validateRepeatAccount, trigger: 'blur' }
                    ],
                    password:[],
                },
                drawerLoading: false,
                sexOption: [{'title':'男','value':0},{'title':'女','value':1}],
            }
        },
        created () {
            this.getData();
        },
        computed: {
            editAuthority() {
                return authorityPath.indexOf(this.editUrl) !== -1;
            },
        },
        methods: {
            /**
             * 获取数据
             */
            getData() {
                let self     = this;
                self.loading = true;
                request.post(self.url, self.search, function(res) {
                    self.loading   = false;
                    self.table     = res.data;
                    self.pageTotal = res.count;
                });
            },
            sortChange(v) {
                this.search = Object.assign({}, this.search, {prop: v.prop , order: v.order});
            },
            /**
             * 打开抽屉
             * @param  {Object} row 当前行
             */
            openDrawer(row = "") {
                let self = this;
                self.drawerData = row === "" ? JSON.parse(JSON.stringify(self.drawerForm)) : JSON.parse(JSON.stringify(row));
                self.drawer = true;
            },
            /**
             * 保存内容
             */
            saveDrawer() {
                let self = this;
                self.$refs.drawerData.validate((valid) => {
                    if (valid) {
                        let requestUrl = typeof self.drawerData.id === 'undefined' ? self.addUrl : self.editUrl;
                        self.drawerLoading = true;
                        request.post(requestUrl, self.drawerData, function(res){
                            self.drawerLoading = false;
                            if (res.status === 'success') {
                                self.getData();
                                self.drawer = false;
                            } else {
                                self.$message({ showClose: true, message: res.message, type: res.status});
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            /**
             * 状态管理
             * @param  {Object} row 当前行
             */
            status(row) {
                let self = this;
                request.post(self.editUrl, {id: row.id, value: row.status, custom_field: 'status'}, function(res) {
                    if (res.status != 'success') {
                        self.$message({ showClose: true, message: res.message, type: res.status});
                        self.getData();
                    } 
                });
            },
            /**
             * 行删除、批量删除
             * @param  {Object} row 当前行
             */
            del(row = "") {
                let self = this;
                let ids  = row === "" ? common.arrayColumn(self.rows,'id') : [row.id]; 
                self.$confirm('确定删除吗？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.post(self.delUrl, {'ids': ids}, function(res){
                        if (res.status === 'success') {
                            self.getData();
                        } else {
                            self.$message({ showClose: true, message: res.message, type: res.status});
                        }
                    });
                }).catch(() => {});
            },
            /**
             * 选中行
             * @param  {Object} rows 多行数
             */
            checkSelected(rows) {
                this.rows = rows;
            },
            /**
             * 关键词/日期搜索
             * @param  {Object} value 搜索内容
             */
            searchData(value) {
                this.search = Object.assign({}, this.search, {page: 1, date: value.date, keyword: value.keyword});
            },
            /**
             * 分页个数改变时
             * @param  {Number} val 每页数量
             */
            pageSizeChange(val) {
                this.search = Object.assign({}, this.search, {pageSize: val});
            },
            /**
             * 分页改变时
             * @param  {String} val 当前页
             */
            pageChange(val) {
                this.search = Object.assign({}, this.search, {page: val});
            },
        },
        watch: {
            drawer(v) {
                if(v){
                    let rulesPassword = [
                        { required: true, message: '请输入用户登录密码', trigger: 'blur' },
                        { min: 6, max: 40, message: '长度在 6 到 40 个字符', trigger: 'blur' }
                    ];
                    this.drawerRules.password = typeof this.drawerData.id === 'undefined' ? rulesPassword : [];
                } else {
                    // 重置表单
                    this.$refs.drawerData.resetFields();
                }
            },
            search() {
                this.getData();
            }
        }
    })
</script>
{include file="$footer" /}